import React, { lazy, useState, useEffect } from 'react';
import {
  AppstoreOutlined,
  HomeOutlined,
  SettingOutlined,
  BookOutlined,
  CarryOutOutlined,
  SendOutlined,
  MedicineBoxOutlined,
  FundOutlined,
  UserOutlined,
  TeamOutlined
} from '@ant-design/icons';
import './App.css';
import axios from 'axios';
// import routes from './router/router';
import { Routes, Route, useNavigate, useLocation } from "react-router-dom";
import { Menu, message, Breadcrumb } from 'antd';
import Home from './pages/Home/Home'
import Auth from './hooks/Auth';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import 'dayjs/locale/zh-cn';

const AccountManage = lazy(() => import('./pages/AccountManage/AccountManage'));
const AddAccount = lazy(() => import('./pages/AddAccount/AddAccount'));
const AddBed = lazy(() => import('./pages/AddBed/AddBed'));
const AddDepartment = lazy(() => import('./pages/AddDepartment/AddDepartment'));
const AddDrug = lazy(() => import('./pages/AddDrug/AddDrug'));
const DepartmentManage = lazy(() => import('./pages/DepartmentManage/DepartmentManage'));
const DepartmentAnalysis = lazy(() => import('./pages/DepartmentAnalysis/DepartmentAnalysis'));
const DiseaseBigData = lazy(() => import('./pages/DiseaseBigData/DiseaseBigData'));
const DispensaryStats = lazy(() => import('./pages/DispensaryStats/DispensaryStats'));
const DoctorList = lazy(() => import('./pages/DoctorList/DoctorList'));
const DoctorReviseInfo = lazy(() => import('./pages/DoctorReviseInfo/DoctorReviseInfo'));
const DoctorScheduling = lazy(() => import('./pages/DoctorScheduling/DoctorScheduling'));
const DrugConsumptionStats = lazy(() => import('./pages/DrugConsumptionStats/DrugConsumptionStats'));
const IntegratedManage = lazy(() => import('./pages/IntegratedManage/IntegratedManage'));
const MedicalEquipmentStats = lazy(() => import('./pages/MedicalEquipmentStats/MedicalEquipmentStats'));
const MedicalSuppliesManage = lazy(() => import('./pages/MedicalSuppliesManage/MedicalSuppliesManage'));
const NurseList = lazy(() => import('./pages/NurseList/NurseList'));
const NurseReviseInfo = lazy(() => import('./pages/NurseReviseInfo/NurseReviseInfo'));
const NurseScheduling = lazy(() => import('./pages/NurseScheduling/NurseScheduling'));
const PrescriptionIssuance = lazy(() => import('./pages/PrescriptionIssuance/PrescriptionIssuance'));
const PrescriptionManage = lazy(() => import('./pages/PrescriptionManage/PrescriptionManage'));
const PrescriptionManage2 = lazy(() => import('./pages/PrescriptionManage2/PrescriptionManage2'));
const RegistrationManage = lazy(() => import('./pages/RegistrationManage/RegistrationManage'));
const RevenueDataSheet = lazy(() => import('./pages/RevenueDataSheet/RevenueDataSheet'));
const DepartmentAnalysisBigData = lazy(() => import('./pages/BigDate/DepartmentAnalysisBigData'));//大数据面板科室分析
const FinancialAnalysis = lazy(() => import('./pages/BigDate/FinancialAnalysis'));//大数据面板科室分析

const items = [
  {
    key: '/home',
    icon: <HomeOutlined />,
    label: '首页',

  },
  {
    key: '/hospitalComplex',
    icon: <AppstoreOutlined />,
    label: '医院综合',
    children: [
      {
        key: '/hospitalComplex/departmentManage',
        label: '科室管理',
        path: '/hospitalComplex/departmentManage',
        element: <DepartmentManage />
      },
      {
        key: '/hospitalComplex/addDepartment',
        label: '添加科室',
        path: '/hospitalComplex/addDepartment',
        element: <AddDepartment />
      },
      {
        key: '/hospitalComplex/departmentAnalysis',
        label: '科室分析',
        path: '/hospitalComplex/departmentAnalysis',
        element: <DepartmentAnalysis />
      }
    ],
  },
  {
    key: '/bigdata',
    icon: <BookOutlined />,
    label: '患者大数据',
    children: [
      {
        key: '/bigdata/drugConsumptionStats',
        label: '药品耗材统计',
        path: '/bigdata/drugConsumptionStats',
        element: <DrugConsumptionStats />
      },
      {
        key: '/bigdata/diseaseBigData',
        label: '疾病大数据',
        path: '/bigdata/diseaseBigData',
        element: <DiseaseBigData />
      },
    ],
  },
  {
    key: '/dynamic',
    icon: <SendOutlined />,
    label: '动态个人',
    children: [
      {
        key: '/dynamic/registrationManage',
        label: '挂号管理',
        path: '/dynamic/registrationManage',
        element: <RegistrationManage />
      },
    ],
  },
  {
    key: '/dispensary',
    icon: <CarryOutOutlined />,
    label: '中西医药房',
    children: [
      {
        key: '/dispensary/prescriptionManage',
        label: '处方综合管理',
        path: '/dispensary/prescriptionManage',
        element: <PrescriptionManage />
      },
      {
        key: '/dispensary/revenueDataSheet',
        label: '营收数据表',
        path: '/dispensary/revenueDataSheet',
        element: <RevenueDataSheet />
      },
      {
        key: '/dispensary/dispensaryStats',
        label: '药房统计',
        path: '/dispensary/dispensaryStats',
        element: <DispensaryStats />
      },
    ],
  },
  {
    key: '/medical',
    icon: <MedicineBoxOutlined />,
    label: '医疗前线',
    children: [
      {
        key: '/medical/prescriptionIssuance',
        label: '处方开具',
        path: '/medical/prescriptionIssuance',
        element: <PrescriptionIssuance />
      },
      {
        key: '/medical/prescriptionManage2',
        label: '处方综合管理',
        path: '/medical/prescriptionManage2',
        element: <PrescriptionManage2 />
      },
      {
        key: '/medical/medicalEquipmentStats',
        label: '医疗器材统计',
        path: '/medical/medicalEquipmentStats',
        element: <MedicalEquipmentStats />
      }
    ],
  },
  {
    key: '/drug',
    icon: <FundOutlined />,
    label: '医疗药品出入库',
    children: [
      {
        key: '/drug/medicalSuppliesManage',
        label: '医疗用品综合管理',
        path: '/drug/medicalSuppliesManage',
        element: <MedicalSuppliesManage />
      },
      {
        key: '/drug/addDrug',
        label: '添加药品耗材',
        path: '/drug/addDrug',
        element: <AddDrug />
      },
    ],
  },
  {
    key: '/doctor',
    icon: <UserOutlined />,
    label: '分级医生',
    children: [
      {
        key: '/doctor/doctorScheduling',
        label: '排班管理',
        path: '/doctor/doctorScheduling',
        element: <DoctorScheduling />
      },
      {
        key: '/doctor/doctorList',
        label: '综合列表',
        path: '/doctor/doctorList',
        element: <DoctorList />
      },
      {
        key: '/doctor/doctorReviseInfo',
        label: '修改个人信息',
        path: '/doctor/doctorReviseInfo',
        element: <DoctorReviseInfo />
      },
    ],
  },
  {
    key: '/nurse',
    icon: <UserOutlined />,
    label: '分级护士',
    children: [
      {
        key: '/nurse/nurseScheduling',
        label: '排班管理',
        path: '/nurse/nurseScheduling',
        element: <NurseScheduling />
      },
      {
        key: '/nurse/nurseList',
        label: '综合列表',
        path: '/nurse/nurseList',
        element: <NurseList />
      },
      {
        key: '/nurse/nurseReviseInfo',
        label: '修改个人信息',
        path: '/nurse/nurseReviseInfo',
        element: <NurseReviseInfo />
      },
    ],
  },
  {
    key: '/bed',
    icon: <SettingOutlined />,
    label: '病床管理',
    children: [
      {
        key: '/bed/addBed',
        label: '添加床位',
        path: '/bed/addBed',
        element: <AddBed />
      },
      {
        key: '/bed/integratedManage',
        label: '综合管理',
        path: '/bed/integratedManage',
        element: <IntegratedManage />
      },
    ],
  },
  {
    key: '/account',
    icon: <TeamOutlined />,
    label: '全账号管理',
    children: [
      {
        key: '/account/accountManage',
        label: '账号管理',
        path: '/account/accountManage',
        element: <AccountManage />
      },
      {
        key: '/account/addAccount',
        label: '添加账号',
        path: '/account/addAccount',
        element: <AddAccount />
      },
    ],
  },
];

const getLevelKeys = (items1) => {
  const key = {};
  const func = (items2, level = 1) => {
    items2.forEach((item) => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};
const levelKeys = getLevelKeys(items);

function App() {
  const location = useLocation();
  const [userInfo, setUserInfo] = useState({
    username: '用户名',
    purview: '权限',
    ctime: '创建时间',
    avatar: '',
  })
  // 面包屑
  // 定义一个函数，递归遍历菜单
  const findActiveMenuItem = (items, path) => {  // 遍历菜单项，找到当前激活的菜单项
    for (const item of items) {
      if (item.key === path || item.path === path) {
        return item;
      }
      if (item.children) {
        const childItem = findActiveMenuItem(item.children, path);
        if (childItem) return { item, childItem }
      }
    }
    return null;
  };
  const [breadcrumb, setBreadcrumb] = useState([])
  const [activeItem, setActiveItem] = useState(null);
  useEffect(() => {
    // console.log(findActiveMenuItem(items, location.pathname))
    setActiveItem(findActiveMenuItem(items, location.pathname));
    
  }, [location, items]);
  useEffect(()=>{
    if(activeItem?.childItem){  // 如果有子菜单
      setBreadcrumb(() => [
        {
          title: '系统'
        },
        {
          title: activeItem?.item?.label
        },
        {
          title: activeItem?.childItem?.label
        }
      ])
    }else{  // 没有子菜单
      setBreadcrumb(() => [
        {
          title: '系统'
        },
        {
          title: activeItem?.label
        }
      ])
    }
  },[activeItem])
  // console.log(route)

  //显示大数据面板
  const [isShow, setIsShow] = useState(false);

  const [stateOpenKeys, setStateOpenKeys] = useState(['/home']);  // 默认展开的菜单项
  const onOpenChange = (openKeys) => {  // 菜单展开/收起时触发的回调函数
    const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
    // open
    if (currentOpenKey !== undefined) {
      const repeatIndex = openKeys
        .filter((key) => key !== currentOpenKey)
        .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);
      setStateOpenKeys(
        openKeys
          // 移出重复项
          .filter((_, index) => index !== repeatIndex)
          // 移出当前项及其子项
          .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey]),
      );
    } else {
      // close
      setStateOpenKeys(openKeys);
    }
  };
  const navigate = useNavigate();
  const handleClick = (e) => {
    navigate(e.key)
  };
  const getUserInfo = () => {  // 获取用户信息
    const userId = localStorage.getItem('dr_id');
    axios.get('http://8.148.7.123:8000/users/getbyid', {
      params: {
        id: userId
      }
    }).then(res => {
      //console.log(res.data.data[0])
      if (res.data.code === 1) {
        const feachData = res.data.data[0]
        setUserInfo({
          username: feachData.name,
          purview: feachData.purview,
          ctime: feachData.ctime.split('').slice(0, 19).join('').replace('T', ' '),
          avatar: feachData.head.replace('http://192.168.109.17:21001', 'http://8.148.7.123:8000')
        })
      }
    }).catch(err => {
      console.log(err)
    })
  }
  const handleExit = () => {  // 退出登录
    localStorage.removeItem('dr_id')
    message.success('退出成功')
    setTimeout(() => {
      navigate('/login')
    }, 1000)
  }
  useEffect(() => {

    getUserInfo()
  }, [])  // 组件挂载时获取用户信息
  useEffect(() => {
    // 根据当前路由设置 isShow 的值
    if (location.pathname !== '/da' && location.pathname !== '/fa') {
      // setIsShow(location.pathname !== '/da');
      setIsShow(true);
    } else {
      setIsShow(false);
    }
  }, [location]); // 依赖项为 location，确保仅在路由变化时更新状态
  // routes.forEach((item) => {
  //   items.push({
  //     label: <Link to={item.path}>{item.label}</Link>,
  //     key: item.path,
  //     icon: item.icon,
  //     children:
  //       item.children &&
  //       item.children.map((child) => {
  //         return {
  //           label: <Link to={item.path + '/' + child.path}>{child.label}</Link>,
  //           key: item.path + '/' + child.path,
  //           icon: child.icon,
  //           children:
  //             child.children &&
  //             child.children.map((sun) => {
  //               return {
  //                 label: (
  //                   <Link to={item.path + '/' + child.path + '/' + sun.path}>
  //                     {sun.label}
  //                   </Link>
  //                 ),
  //                 key: item.path + '/' + child.path + '/' + sun.path,
  //                 icon: sun.icon,
  //               }
  //             }),
  //         }
  //       }),
  //   })
  // });

  return (
    <ConfigProvider locale={zhCN}>
      <div className={`layout ${isShow ? 'appear' : 'noShow'}`}>
        <header className="header">
          <div className='hospital_name'></div>
          <div className="user_info">
            <div>{userInfo.ctime}</div>
            <div className="avatar">
              <div className="exit" onClick={handleExit}>退出登录</div>
              <img alt="头像" src={userInfo.avatar} />
            </div>
            <div>
              <div className='username'>{userInfo.username}</div>
              <div className='purview'>{userInfo.purview}</div>
            </div>
          </div>
        </header>
        <section className="content">
          <div className="left">
            <Menu
              className='menu'
              mode="inline"
              defaultSelectedKeys={['sub1-1']}
              openKeys={stateOpenKeys}
              onOpenChange={onOpenChange}
              items={items}
              onClick={handleClick}
            >

            </Menu>
          </div>
          <div className="right">
            <div className='right-header'>
              <Breadcrumb
                items={breadcrumb}
              />
            </div>
            <div className='right-content'>
              <Routes>
                <Route path="/" element={<Auth><Home /></Auth>}></Route>
                <Route path="/home" element={<Auth><Home /></Auth>}></Route>
                <Route path="/account/accountManage" element={<Auth><AccountManage /></Auth>}></Route>
                <Route path="/account/addAccount" element={<Auth><AddAccount /></Auth>}></Route>
                <Route path="/bed/addBed" element={<Auth><AddBed /></Auth>}></Route>
                <Route path="/hospitalComplex/addDepartment" element={<Auth><AddDepartment /></Auth>}></Route>
                <Route path="/drug/addDrug" element={<Auth><AddDrug /></Auth>}></Route>
                <Route path="/hospitalComplex/departmentManage" element={<Auth><DepartmentManage /></Auth>}></Route>
                <Route path="/hospitalComplex/departmentAnalysis" element={<Auth><DepartmentAnalysis /></Auth>}></Route>
                <Route path="/bigdata/diseaseBigData" element={<Auth><DiseaseBigData /></Auth>}></Route>
                <Route path="/dispensary/dispensaryStats" element={<Auth><DispensaryStats /></Auth>}></Route>
                <Route path="/doctor/doctorList" element={<Auth><DoctorList /></Auth>}></Route>
                <Route path="/doctor/doctorReviseInfo" element={<Auth><DoctorReviseInfo /></Auth>}></Route>
                <Route path="/doctor/doctorScheduling" element={<Auth><DoctorScheduling /></Auth>}></Route>
                <Route path="/bigdata/drugConsumptionStats" element={<Auth><DrugConsumptionStats /></Auth>}></Route>
                <Route path="/bed/integratedManage" element={<Auth><IntegratedManage /></Auth>}></Route>
                <Route path="/medical/medicalEquipmentStats" element={<Auth><MedicalEquipmentStats /></Auth>}></Route>
                <Route path="/drug/medicalSuppliesManage" element={<Auth><MedicalSuppliesManage /></Auth>}></Route>
                <Route path="/nurse/nurseList" element={<Auth><NurseList /></Auth>}></Route>
                <Route path="/nurse/nurseReviseInfo" element={<Auth><NurseReviseInfo /></Auth>}></Route>
                <Route path="/nurse/nurseScheduling" element={<Auth><NurseScheduling /></Auth>}></Route>
                <Route path="/medical/prescriptionIssuance" element={<Auth><PrescriptionIssuance /></Auth>}></Route>
                <Route path="/dispensary/prescriptionManage" element={<Auth><PrescriptionManage /></Auth>}></Route>
                <Route path="/medical/prescriptionManage2" element={<Auth><PrescriptionManage2 /></Auth>}></Route>
                <Route path="/dynamic/registrationManage" element={<Auth><RegistrationManage /></Auth>}></Route>
                <Route path="/dispensary/revenueDataSheet" element={<Auth><RevenueDataSheet /></Auth>}></Route>
              </Routes>
            </div>
          </div>
        </section>
      </div>
      <div className={`big_data_context ${isShow ? 'noShow' : 'appear'}`}>
        <Routes>
          <Route path="/da" element={<DepartmentAnalysisBigData />}></Route>
          <Route path="/fa" element={<FinancialAnalysis />}></Route>
        </Routes>
      </div>
      {/* <Routes>
        <Route path="/" element={<Home />} /> */}
      {/* 为每个子菜单项创建路由 */}
      {/* {items.map((item) => (
          <Route
            key={item.key}
            path={`/${item.key}`}
            element={
              <div>
                {item.children ? (
                  // 如果有子菜单，渲染子菜单的 NavLink
                  <Menu
                    mode="inline"
                    defaultSelectedKeys={['sub1-1']}
                    openKeys={stateOpenKeys}
                    onOpenChange={onOpenChange}
                    items={item.children}
                  />
                ) : (
                  // 否则渲染对应的页面组件
                  <NavLink to={`/${item.key}`}>{item.label}</NavLink>
                )}
              </div>
            }
          />
        ))} */}
      {/* 为每个子菜单项的子菜单创建路由 */}
      {/* {items.flatMap((item) =>
          item.children
            ? item.children.map((child) => (
                <Route
                  key={child.key}
                  path={`/${item.key}/${child.key}`}
                  element={<NavLink to={`/${item.key}/${child.key}`}>{child.label}</NavLink>}
                />
              ))
            : null
        )}
      </Routes> */}
    </ConfigProvider>
  )
}

export default App
